home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C23 / Cleanup.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.6 KB  |  69 lines

  1. //: C23:Cleanup.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Exceptions clean up objects
  7. #include <fstream>
  8. #include <exception>
  9. #include <cstring>
  10. using namespace std;
  11. ofstream out("cleanup.out");
  12.  
  13. class Noisy {
  14.   static int i;
  15.   int objnum;
  16.   static const int sz = 40;
  17.   char name[sz];
  18. public:
  19.   Noisy(const char* nm="array elem") throw(int){
  20.     objnum = i++;
  21.     memset(name, 0, sz);
  22.     strncpy(name, nm, sz - 1);
  23.     out << "constructing Noisy " << objnum
  24.       << " name [" << name << "]" << endl;
  25.     if(objnum == 5) throw int(5);
  26.     // Not in exception specification:
  27.     if(*nm == 'z') throw char('z');
  28.   }
  29.   ~Noisy() {
  30.     out << "destructing Noisy " << objnum
  31.       << " name [" << name << "]" << endl;
  32.   }
  33.   void* operator new[](size_t sz) {
  34.     out << "Noisy::new[]" << endl;
  35.     return ::new char[sz];
  36.   }
  37.   void operator delete[](void* p) {
  38.     out << "Noisy::delete[]" << endl;
  39.     ::delete []p;
  40.   }
  41. };
  42.  
  43. int Noisy::i = 0;
  44.  
  45. void unexpected_rethrow() {
  46.   out << "inside unexpected_rethrow()" << endl;
  47.   throw; // Rethrow same exception
  48. }
  49.  
  50. int main() {
  51.   set_unexpected(unexpected_rethrow);
  52.   try {
  53.     Noisy n1("before array");
  54.     // Throws exception:
  55.     Noisy* array = new Noisy[7];
  56.     Noisy n2("after array");
  57.   } catch(int i) {
  58.     out << "caught " << i << endl;
  59.   }
  60.   out << "testing unexpected:" << endl;
  61.   try {
  62.     Noisy n3("before unexpected");
  63.     Noisy n4("z");
  64.     Noisy n5("after unexpected");
  65.   } catch(char c) {
  66.     out << "caught " << c << endl;
  67.   }
  68. } ///:~
  69.